package com.ks.system.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ks.handler.BusinessException;
import com.ks.response.ResultCode;
import com.ks.system.entity.Role;
import com.ks.system.enums.RoleStatusEnum;
import com.ks.system.mapper.RoleMapper;
import com.ks.system.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author ks
 * @since 2020-12-01
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Override
    public Page<Role> getRoleList(String roleName, Page<Role> page) {
        List<Role> roleList = this.baseMapper.getRoleList(roleName, page);
        //将刚刚通过动态sql获取的数据设置给分页的记录就行了
        return page = page.setRecords(roleList);
    }

    @Override
    public void exportUserExcel(HttpServletResponse response, List<Role> roles) throws IOException {
        //----- 写入excel文件
        String exportFileName = "RoleInfo.xlsx";
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.ms-excel");
        response.addHeader("Content-Disposition", "attachment;filename=" + exportFileName);
        EasyExcel.write(response.getOutputStream(), Role.class)
                .sheet("用户角色信息")
                //自动列宽
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .doWrite(roles);
    }

    @Override
    public void addRole(Role role) {
        //角色名称
        String roleName = role.getRoleName();

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("role_name", roleName);
        Integer count = this.baseMapper.selectCount(wrapper);
        //判断用户是否已经存在
        if(count != 0){
            //存在即抛出一个异常信息
            throw  new BusinessException(ResultCode.ROLE_ACCOUNT_ALREADY_EXIST.getCode(),
                    ResultCode.ROLE_ACCOUNT_ALREADY_EXIST.getMessage());
        }
        role.setStatus(RoleStatusEnum.AVAILABLE.getStatusCode());
        role.setDeleted(0);
        this.baseMapper.insert(role);
    }

    @Override
    public void delRole(Integer id) {

    }
}
